﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;
using Windows.Data.Xml.Dom;
using English.Common;
using English.Model;

namespace English.ViewModel
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<TermDefinition> _definitions;
        public ObservableCollection<TermDefinition> Definitions
        {
            get { return _definitions; }
            set
            {
                _definitions = value;
                OnPropertyChanged("Definitions");
            }
        } 

        private bool _definitionsLoaded;
        public bool DefinitionsLoaded
        {
            get
            {
                return this._definitionsLoaded;
            }
            set
            {
                _definitionsLoaded = value;
                OnPropertyChanged("DefinitionsLoaded");
            }
        }

        private static async Task<ObservableCollection<TermDefinition>> _loadDedinitionsTask()
        {
            var client = new HttpClient();
            var url = String.Format(STANDS4.DefinitionsApiUrl,STANDS4.SiteUrl, STANDS4.UserId, STANDS4.Token, "table");
            var getStringTask = client.GetStringAsync(url);
            var urlContents = await getStringTask;
            var serializer = new XmlSerializer(typeof(TermDefinitions));
            var document = XDocument.Parse(urlContents.Replace("<results>", "<root><results>") + "</root>");
            var rootXML = (TermDefinitions)serializer.Deserialize(document.CreateReader());
            return rootXML.Collection;
        }

        public async Task<bool> LoadDefinitions()
        {
            var defs = await _loadDedinitionsTask();
            Definitions = new ObservableCollection<TermDefinition>(defs);
            DefinitionsLoaded = true;
            return true;
        }

        #region Prorerty changed handler
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
        #endregion
    }
}
